package redis

import (
	"Bluebell/models"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

func GetIDsFromKey(key string, page, size int64) ([]string, error) {
	start := (page - 1) * size
	end := start + size
	return client.ZRevRange(key, start, end).Result()
}

func GetPostIDsInOrder(p *models.ParamsPostList) ([]string, error) {
	key := GetRedisKey(KeyPostTimeZSet)
	if p.Order == models.OrderScore {
		key = GetRedisKey(KeyPostScoreZSet)
	}
	return GetIDsFromKey(key, p.Page, p.Size)
}

func GetPostVoteData(ids []string) (data []int64, err error) {
	//data := make([]int64, 0, len(ids))
	//for _, id := range ids {
	//	key := GetRedisKey(KeyPostVotedZSetPrefix + id)
	//	v := client.ZCount(key, "1", "1").Val()
	//	data = append(data, v)
	//}

	//使用pipeline一次发送多个数据
	pipeline := client.Pipeline()
	for _, id := range ids {
		key := GetRedisKey(KeyPostVotedZSetPrefix + id)
		pipeline.ZCount(key, "1", "1")
	}
	cmders, err := pipeline.Exec()
	if err != nil {
		return nil, err
	}
	data = make([]int64, 0, len(cmders))
	for _, cmder := range cmders {
		v := cmder.(*redis.IntCmd).Val()
		data = append(data, v)
	}
	return
}

func GetCommunityPostIDsInOrder(p *models.ParamsPostList) ([]string, error) {
	orderKey := GetRedisKey(KeyPostTimeZSet)
	if p.Order == models.OrderScore {
		orderKey = GetRedisKey(KeyPostScoreZSet)
	}

	//使用zinterstore把分区的帖子set与帖子分数的zset生成新的zset
	key := orderKey + strconv.Itoa(int(p.CommunityID))
	//社区key
	cKey := GetRedisKey(KeyCommunitySetPF + strconv.Itoa(int(p.CommunityID)))
	if client.Exists(orderKey).Val() < 1 {
		pipeline := client.Pipeline()
		pipeline.ZInterStore(key, redis.ZStore{
			Aggregate: "MAX",
		}, cKey, orderKey)
		pipeline.Expire(key, 60*time.Second)
		_, err := pipeline.Exec()
		if err != nil {
			return nil, err
		}
	}
	return GetIDsFromKey(orderKey, p.Page, p.Size)
}
